/*************************************************************************
 * @file test.cpp
 * @auth wuwei
 * @created_time Mon 05 Nov 2018 01:59:29 PM CST
 * @brief test program build cmd: "g++ -std=c++11 test.cpp -L. httplib.a -lpthread -o client"
 ************************************************************************/

#include "httplib.h"

#include <string.h>
#include <iostream>
#include <thread>
using namespace std;


int g_nSend = 0;
int g_nRecv = 0;

void CallBack(int anHandle, int anStatus, char* apszData, int anNum) {
    //cout << "apszData:" << apszData << endl;
    //cout << "c++ call back get handle:" << anHandle << "  status:" << anStatus << " num:" << anNum << endl;
    ++ g_nRecv;
    ReleaseHandle(anHandle);
}

void waitThread(int an) {
    while(true){
        GoInt32 nType, nError, nUserData, nHandle; 
        WaitForEvent(&nType, &nError, &nUserData, &nHandle);
        cout << "type:" << nType << "  handle:" << nHandle << endl;
        {
            char* pStr = GetSResult(nHandle);
            cout << "pStr len:" << strlen(pStr) << endl;
            //cout << pStr << endl;
            free(pStr);
        }

        ReleaseHandle(nHandle);
    }
}

void dumpThread(int an) {
    while(true) {
        cout << "send:" << g_nSend << " recv :" << g_nRecv << endl;
        std::chrono::milliseconds dura(1000);
        std::this_thread::sleep_for(dura);
    }
}

int main () {
    auto worker = std::thread(waitThread, 1000);
    auto dumper = std::thread(dumpThread, 1000);

    //char* strUrl = "http://www.baidu.com";
    //char* strUrl = "http://120.132.38.79:8080/iii/bbb?name=aaa&bbb=ffff";
    char* strUrl = "http://123.59.20.214:1986/api/v1/test/getok";
    char* strMethod = "GET";
    char* strBody = "name=aaa&ps=bbb";

    //std::chrono::milliseconds dura(1);
    std::chrono::microseconds dura(5);
    for(;;) {
        GoInt32 nHandle = CreateRequest(strMethod, strUrl, strBody, (void*)CallBack);
        //cout << "handle :" << nHandle << endl;
        if (-1 == nHandle)
            continue;
        ++ g_nSend;
        DoRequest(nHandle);
        std::this_thread::sleep_for(dura);
    } 

    worker.join();
    dumper.join();
}
